/*
 * Copyright (C) 2012 Rothens
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package rpg.server.net;

import java.io.IOException;
import java.net.Socket;
import java.util.Random;
import rpg.server.RPGServer;
import rpg.server.packets.Packet;
import rpg.server.packets.Packet1Login;
import rpg.server.packets.Packet2Handshake;

/**
 * rothens.tumblr.com
 * @author Rothens
 */
public class LoginHandler extends NetworkHandler {
	
	public NetworkManager netmanager;
	public boolean finishedProcessing;
	private Packet1Login loginpacket;
	private RPGServer rpgs;
	private int time;
	private String username;
	
	public LoginHandler(RPGServer rpgs, Socket socket, String name) throws IOException{
		finishedProcessing = false;
		time = 0;
		username = null;
		this.rpgs = rpgs;
		netmanager = new NetworkManager(socket, name, this);
		loginpacket = null;
	}
	
	public void tryLogin() {
		if(loginpacket != null){
			doLogin(loginpacket);
			loginpacket = null;
		}
		if(time++ == 600){
			kickUser("Timed out.");
		} else {
			netmanager.processReadPackets();
		}
	}
	
	public void kickUser(String reason){
		netmanager.serverShutdown();
		finishedProcessing = true;
	}
	
	public void handleLogin(Packet1Login loginpacket){
		username = loginpacket.username;
		if(loginpacket.version != RPGServer.VERSION){
			if(loginpacket.version > RPGServer.VERSION){
				kickUser("Server is outdated!");
			} else {
				kickUser("Client is outdated.");
			}
			return;
		}
		doLogin(loginpacket);
	}

	@Override
	public void handleHandshake(Packet2Handshake handshakepacket) {
		netmanager.addToSendQueue(new Packet2Handshake("-"));
	}
	
	
	
	public void doLogin(Packet1Login loginpacket){
		finishedProcessing = true;
	}

	@Override
	public void registerPacket(Packet packet) {
		kickUser("DO NOT!");
	}
	
	

	@Override
	public boolean isServerHandler() {
		return true;
	}
	
	public String getUserIP(){
		return netmanager.getRemoteAddress().toString();
	}
	
	static Packet1Login setLoginPacket(LoginHandler loginhandler, Packet1Login loginpacket){
		return loginhandler.loginpacket = loginpacket;
	}
	
}
